package com.tencent.txcc.mq;

import com.alibaba.fastjson.JSON;
import com.tencent.txcc.domain.MessageSms;
import com.tencent.txcc.dto.SendOnLineMessageDto;
import com.tencent.txcc.dto.UserMessageDto;
import com.tencent.txcc.service.IMessageSmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
@RocketMQMessageListener(
        consumerGroup="course-sms-consumer-group",
        topic="smsmessage-topic",
        selectorExpression="smsmessage-tag"
)
public class SmsMessageConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IMessageSmsService messageSmsService;

    @Override
    public void onMessage(MessageExt messageExt) {
        byte[] body = messageExt.getBody();
        String str = new String(body, StandardCharsets.UTF_8);
        SendOnLineMessageDto sendOnLineMessageDto = JSON.parseObject(str, SendOnLineMessageDto.class);
        saveSmsMessage(sendOnLineMessageDto);
        log.info("发送短信成功");
    }

    private void saveSmsMessage(SendOnLineMessageDto sendOnLineMessageDto) {
        MessageSms message = new MessageSms();
        message.setTitle(sendOnLineMessageDto.getTitle());
        message.setContent(sendOnLineMessageDto.getContent());
        message.setSendTime(new Date());
        List<UserMessageDto> userMessageDto = sendOnLineMessageDto.getUserMessageDto();
        userMessageDto.forEach(e->{
            message.setUserId(e.getUserId());
            message.setPhone(e.getContact());
            messageSmsService.insert(message);
        });

    }

}
